package org.lqk.pool.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@ComponentScan("org.lqk.pool.netty")
@PropertySource("classpath:netty-client.properties")
public class NettyClientConfig {
	@Value("${client.connect.host}")
	private String host;
	@Value("${client.connect.port}")
	private int port;

	@Value("${client.worker.thread.count}")
	private int workerCount;
	
	@Value("${client.log4j.configuration}")
	private String log4jConfiguration;

	@Autowired
	private NettyClientChannelInitializer nettyClientChannelInitializer;
	
	private static Logger log = LoggerFactory.getLogger(NettyClientConfig.class);

	@SuppressWarnings("unchecked")
	@Bean(name = "clientBootstrap")
	public Bootstrap bootstrap() {
		log.debug("init bootstrap");
		Bootstrap bootstrap = new Bootstrap();
		bootstrap
				.group(workerGroup())
				.remoteAddress(host,port)
				.channel(NioSocketChannel.class)
				.handler(nettyClientChannelInitializer);
		return bootstrap;
	}

	@Bean(name = "clientWorkerGroup", destroyMethod = "shutdownGracefully")
	public NioEventLoopGroup workerGroup() {
		return new NioEventLoopGroup(workerCount);
	}

	/**
	 * Necessary to make the Value annotations work.
	 * 
	 * @return
	 */
	@Bean
	public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
		return new PropertySourcesPlaceholderConfigurer();
	}
}
